<?php

namespace app\logic;

use app\components\helpers\ArrayHelper;
use app\forms\ContactForm;
use app\models\Contacts;
use yii\web\HttpException;

/**
 * 客户联系人逻辑
 */
class ContactLogic extends BaseLogic
{
    public static function index($param)
    {
        $form = new ContactForm();
        $form->setScenario('index');
        $form->setAttributes($param);
        if (!$form->validate()) {
            foreach ($form->getErrors() as $key => $val) {
                $form->$key = '';
            }
        }
        $attr = $form->getAttributes();
        return Contacts::getListBy($attr);
    }

    /**
     * 创建联系人
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = self::_validate(new ContactForm(), $param, 'create');
        $attr = $form->getAttributes();


        dump($attr);
        $arr = self::_setColumn($attr);
        unset($arr['contact']['id']);
        Contacts::performCreate($arr['contact'], $arr['data']);
        throw new HttpException(200);
    }

    /**
     * 编辑联系人
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = self::_validate(new ContactForm(), $param, 'update');
        $attr = $form->getAttributes();
        // 主键
        $id = $attr['id'];
        $arr = self::_setColumn($attr);
        $contact = $arr['contact'];
        $data = $arr['data'];
        $contact['updated_by'] = user()->id;
        $contact['updated_at'] = $_SERVER['REQUEST_TIME'];
        Contacts::performUpdate($id, $contact, $data);
        throw new HttpException(200);
    }

    /**
     * 删除联系人
     * @param $param
     * @throws HttpException
     */
    public static function delete($param)
    {
        $form = self::_validate(new ContactForm(), $param, 'delete');
        $arr['is_deleted'] = 1;
        $arr['deleted_by'] = user()->id;
        $arr['deleted_at'] = $_SERVER['REQUEST_TIME'];
        Contacts::updateByPk($arr, $form['id']);
        throw new HttpException(200);
    }

    /**
     * 将主表与附表的数据拆分开
     * @param $attr
     * @return array
     */
    public static function _setColumn($attr)
    {
        $attr = ArrayHelper::humpToUnderline($attr);
        $keys = ['country_id', 'province_id', 'city_id', 'district_id', 'street', 'description'];
        $data = array_intersect_key($attr, array_flip($keys)); // 附表
        $contact = array_diff_key($attr, array_flip($keys)); // 主表
        return ['data' => $data, 'contact' => $contact];
    }
}